<?php

namespace app\api\home;

use think\Db;
use think\Cache;
use think\Session;
use app\example\model\CollectArticle as NewsModel;

class Articles extends Base
{
    private $redis = null;

    protected function _initialize()
    {
        parent::_initialize();
        $this->redis = Cache::getHandler();
    }

    public function index()
    {
        //Session::set('user.id', 1111);
        $limit = config('comment_limit');
        $page = input('param.page/d', 1);
        $data = [
            'limit' => $limit,
            'page' => $page,
        ];
        $data['total'] = NewsModel::where('status', '=', 1)->count();
        $data['articles'] = NewsModel::where('status', '=', 1)->limit($limit)->page($page)->select();

        return $this->apiReturn('', 0, $data);
    }

    public function read()
    {
        $_id = get_num();

        $data = NewsModel::get($_id);
        if (!$data || $data->status == 0) {
            return $this->apiReturn('文章不存在', 1);
        }

        return $this->apiReturn('', 0, $data);
    }

    public function vote()
    {
        $start_time = strtotime('2018-12-25 00:00:00');
        $end_time = strtotime('2018-12-31 23:59:59');
        $now_time = strtotime(date('Y-m-d H:i:s', time()));

        if ($start_time > $now_time) {
            return $this->apiReturn('投票还未开始', 1);
        }

        if ($end_time < $now_time) {
            return $this->apiReturn('投票已结束', 1);
        }
        if (!$this->checkReferer()) {
            return $this->apiReturn('非法请求', 1);
        }
        if (!request()->isPost()) {
            return $this->apiReturn('方法不存在', 1);
        }
        $aid = input('post.aid/d');
        $login_user = session('login_user');
        if (empty($login_user) || empty($login_user['id'])) {
            return $this->apiReturn('请先登录', 100);
        }
        if (empty($aid)) {
            return $this->apiReturn('文章不存在', 1);
        }
        $uid = $login_user['id'];
        if ($this->checkUserVoteToArticle($aid, $uid)) {
            return $this->apiReturn('今天已经给他投过票啦!', 1);
        }
        if ($this->checkUserVoteCount($uid)) {
            return $this->apiReturn('投票失败，每天最多投5票!', 1);
        }

        $row = Db::name('collect_article')->where('id', $aid)->find();
        if (empty($row)) {
            return $this->apiReturn('文章不存在', 1);
        }

        Db::startTrans();
        try {
            Db::name('collect_article')->where('id', $aid)->inc('vote_num')->update();
            Db::name('collect_article')->where('id', $aid)->update(['contribute_time' => date('Y-m-d H:i:s', time())]);

            $data = ['aid' => $aid, 'uid' => $uid];
            Db::name('collect_vote')->insert($data);
            // 提交事务
            Db::commit();
            $day = date('Ymd', time());
            $articleVoteList = sprintf(config('article_to_day_vote'), $aid, $day);
            $userVoteList = sprintf(config('user_to_day_article_list'), $uid, $day);
            $this->redis->sAdd($articleVoteList, $uid);
            $this->redis->sAdd($userVoteList, $aid);

            return $this->apiReturn('投票成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return $this->apiReturn('数据库操作失败'.$e->getMessage(), 1);
        }
    }

    private function checkUserVoteToArticle($aid, $uid, $day = null)
    {
        $day = empty($day) ? date('Ymd', time()) : $day;
        if ($this->redis->sismember(sprintf(config('article_to_day_vote'), $aid, $day), $uid)) {
            return true;
        }

        return false;
    }

    private function checkUserVoteCount($uid, $day = null)
    {
        $day = empty($day) ? date('Ymd', time()) : $day;
        $count = $this->redis->scard(sprintf(config('user_to_day_article_list'), $uid, $day));
        if ($count >= 5) {
            return true;
        }

        return false;
    }
}
